package com.softeware.service;

import com.softeware.dao.BaseDao;
import com.softeware.dao.message.MessageDao;
import com.softeware.dao.message.MessageDaoImpl;
import com.softeware.pojo.Message;
import jakarta.servlet.ServletContext;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class MessageService {
    private MessageDao messageDao;
    public MessageService(){
        this.messageDao = new MessageDaoImpl();
    }
    public void addMessage(Message message, ServletContext context) {
        Connection connection = null;
        try {
            connection = BaseDao.getConnection();
            int updataRows = messageDao.addMessages(connection,message);
            if(updataRows>0){
                System.out.println("add message success");
            }else{
                System.out.println("add message failed!");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
    }

    public List<Message> getMessages(ServletContext context) {
        List<Message> messages = null;
        Connection connection = null;
        try{
            connection = BaseDao.getConnection();
            messages = messageDao.getAllMessages(connection);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            BaseDao.closeResource(connection,null,null);
        }
        return messages;
    }
}
